<template>
  <div class="container" v-loading="loading">
    <CLTable
      :pageQuery="queryParams"
      :fields="referenceFields"
      :initial-data="tableData"
      line-height="low"
      :router-fields="routerFields"
      :table-config="tableConfig"
      :more-actions="moreActions"
      @node-selected="handleNodeSelected"
      @on-more-action="handleMoreAction"
      @pagerChange="pagerChange"
    >
    </CLTable>
  </div>
</template>

<script setup lang="ts">
  import { ref, onMounted } from "vue";
  import { ElMessage } from "element-plus";
  import CLTable from "@/components/CLTable/index.vue";
  import { getTaskList, deleteTaskRelation, getPermission } from "./api.ts";
  import { useRouter } from "vue-router";
  import subSvg from "@/assets/wbs/sub.svg";

  const props = defineProps(["detail", "subTask"]);
  // 响应式数据
  const loading = ref(false);
  const tableData = ref<any[]>([]);
  const selectedFiles = ref<any[]>([]);

  const router = useRouter();
  const routerFields = ref(["code"]);

  /**
   * @description 获取权限
   */
  const havePermission = async () => {
    try {
      const res = await getPermission(props.detail?.projectId, "TASK_TYPE");
      return res;
    } catch (error) {
      return false;
    }
  };

  /**
   * @description 跳转子任务页面  --新页签
   */
  const goSubView = async (item: any) => {
    const flag = await havePermission();
    if (flag) {
      const href = router.resolve({
        name: "SubTaskView",
        query: {
          projectId: props.detail.projectId,
          taskId: item.id,
        },
      });
      window.open(href.href, "_blank");
    } else {
      ElMessage.error("⽆权限，需向管理员申请权限");
    }
  };

  /**
   * @description 监听分页变化
   */
  const pagerChange = (args: any) => {
    loadData(args.currentPage, args.pageSize);
  };
  // CLTable 字段配置
  const referenceFields = ref<any[]>([
    {
      id: 1,
      name: "编号",
      field: "code",
      typex: "imagetext",
      invisible: true,
      checked: true,
      disable: false,
    },
    {
      id: 2,
      name: "标题",
      field: "status",
      type: "text",
      invisible: true,
      checked: true,
      disable: false,
    },
    {
      id: 3,
      name: "状态",
      field: "remark",
      type: "text",
      invisible: true,
      checked: true,
      disable: false,
    },
    {
      id: 4,
      name: "优先级",
      field: "priority",
      type: "text",
      invisible: true,
      checked: true,
      disable: false,
    },
    {
      id: 5,
      name: "负责人",
      field: "curator",
      type: "text",
      invisible: true,
      checked: true,
      disable: false,
    },
  ]);

  // CLTable 配置
  const tableConfig = ref({
    tableH: "calc(100vh - 200px)",
    rightFrozenColCount: 1, // 冻结后面列数
    page: {
      showOperationsColumn: true,
      enable: true,
      pageSizes: [10, 20, 50, 100],
      size: "small",
      disabled: false,
      background: true,
      layout: "total, sizes, prev, pager, next, jumper",
    },
    OperationsColumnMode: "textIcon", // 操作列模式，text为文本模式
    OperationsColumnWidth: 50, //自定义操作列宽度
    borderMode: "none", // 表格边框模式，none为无边框
  });

  // 更多操作配置
  const moreActions = ref([{ key: "unbind", label: "解绑" }]);
  const handleMoreAction = (actionKey: string, node: any) => {
    const KEYMAP: any = {
      unbind: handleUnBind,
      code: goSubView,
    };
    KEYMAP[actionKey]?.(node);
  };

  // 计算属性
  const queryParams = ref({
    pageNo: 1,
    pageSize: 20,
    total: 0,
  });

  // 方法
  const loadData = async (numberPage: number, sizePage: number) => {
    loading.value = true;
    try {
      const params = {
        conditions: [
          {
            field: "parentTaskId",
            operator: "=",
            value: props.detail.id,
          },
        ],
        pageNo: numberPage ?? 1,
        pageSize: sizePage ?? 10,
      };

      // 如果需要调用真实 API，取消下面的注释
      const { result, pageNo, pageSize, total } = await getTaskList(params);
      queryParams.value = {
        pageNo,
        pageSize,
        total,
      };
      tableData.value =
        result.map((ele: any) => ({ ...ele, imageUrl: subSvg })) ?? [];
      //需要触发子项目相关的改便
      props.subTask("subTask", result);
    } catch (error) {
      ElMessage.error("加载数据失败");
    } finally {
      loading.value = false;
    }
  };

  const handleNodeSelected = (nodes: any[]) => {
    selectedFiles.value = nodes;
  };

  /**
   * @description 处理解绑逻辑
   */
  const handleUnBind = async (node: any) => {
    loading.value = true;
    try {
      const params = {
        asChildOfParentId: "",
        id: node.id,
      };
      await deleteTaskRelation(params);
      loadData(1, 20);
    } catch (error) {}
  };
  // 生命周期
  onMounted(async () => {
    loadData(1, 20);
  });

  // 暴露方法给父组件
  defineExpose({
    loadData,
    refresh: loadData,
  });
</script>

<style scoped lang="scss">
  .container {
    box-sizing: border-box;
    padding-right: 10px;
    margin-top: 2px;
    .table-toolbar {
      display: flex;
      flex-direction: row;
      align-items: center;
      padding: 10px 0px;
      color: #5e5e5e;
      font-size: 14px;
    }
  }

  .relation {
    display: flex;
    flex-direction: row;
    align-items: center;
    justify-content: space-between;
  }
</style>
